package com.shoppingmall.handler;

import com.alibaba.fastjson.JSONObject;
import com.shoppingmall.commons.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        String ErrMsG="";
        if (UsernameNotFoundException.class==exception.getClass()){
            ErrMsG="用户名不存在";
        }else if (exception.getClass()== BadCredentialsException.class){
            ErrMsG="密码错误";
        }else if (exception.getClass()== LockedException.class){
            ErrMsG="账户被锁定";
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSONObject.toJSON(Result.fail(401,ErrMsG)));
    }
}
